import { getResultsAPI, getSuggestsAPI } from '@/api/search';
import { AppDispatch } from '..';

export const getSuggestsAction = (q: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSuggestsAPI(q);
    dispatch({ type: 'search/saveSuggests', payload: res.data.options });
  };
};

export const clearSuggestsAction = () => {
  return {
    type: 'search/saveSuggests',
    payload: [],
  };
};

export const saveHistoriesAction = (keyword: string) => {
  return {
    type: 'search/saveHistories',
    payload: keyword,
  };
};

export const clearHistoriesAction = () => {
  return {
    type: 'search/clearHistories',
  };
};

export const getResultsAction = (q: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getResultsAPI({ q });
    dispatch({ type: 'search/saveResults', payload: res.data });
  };
};

// 3. 封装一个请求更多数据的异步aciton
export const updateResultsAction = (q: string, page: number, per_page = 10) => {
  return async (dispatch: AppDispatch) => {
    const res = await getResultsAPI({ q, page, per_page });
    // 4. dispatch触发,保存更多的数据
    dispatch({ type: 'search/updateResults', payload: res.data });
  };
};
